<template>
  <div>
    <table class="table table-sm table-bordered approve-table" v-loading="loading">
      <colgroup>
        <col width="20%" />
        <col width="30%" />
        <col width="20%" />
        <col width="30%" />
      </colgroup>
      <tbody>
        <tr class="bg-light">
          <td colspan="4" class="text-center py-2">退费信息</td>
        </tr>
        <tr>
          <td>退费时间</td>
          <td :class="tdClass">
            <span v-if="isView">{{ formData.pay_time }}</span>
            <el-date-picker
              v-else
              type="date"
              class="w-100"
              value-format="yyyy-MM-dd"
              placeholder="退费时间"
              v-model="formData.pay_time"
            ></el-date-picker>
          </td>
          <td>退费金额</td>
          <td :class="tdClass">
            <span v-if="isView">{{ formData.pay_funds || '-' }} 元</span>
            <el-input
              v-else
              v-model="formData.pay_funds"
              placeholder="退费金额"
              v-input-number="{ min: 0, fixed: 2 }"
            >
              <span slot="append">元</span>
            </el-input>
          </td>
        </tr>
        <tr>
          <td>收款银行名称</td>
          <td :class="tdClass">
            <span v-if="isView">{{ formData.receive_bank_name }}</span>
            <el-input
              v-else
              v-model="formData.receive_bank_name"
              placeholder="收款银行名称"
            ></el-input>
          </td>
          <td>收款银行账户名</td>
          <td :class="tdClass">
            <span v-if="isView">{{ formData.receive_account_name }}</span>
            <el-input
              v-else
              v-model="formData.receive_account_name"
              placeholder="收款银行账户名"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td>收款银行账号</td>
          <td :class="tdClass" colspan="3">
            <span v-if="isView">{{ formData.receive_account }}</span>
            <el-input
              v-else
              v-model="formData.receive_account"
              placeholder="收款银行账号"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td>退费说明</td>
          <td colspan="3" :class="tdClass" class="text-left">
            <span v-if="isView">{{ formData.remark }}</span>
            <el-input
              v-else
              v-model="formData.remark"
              type="textarea"
              :rows="5"
              placeholder="退费说明"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td>退费附件</td>

          <td colspan="3" class="text-left" :class="tdClass">
            <template v-if="isView">
              <div v-for="file in areadyFiles" :key="file.url" class="d-flex">
                <attach-item :attach-data="file"></attach-item>
              </div>
            </template>
            <template v-else>
              <div class="d-flex align-items-stretch p-2">
                <div class="mr-3">
                  <input
                    type="file"
                    ref="uploadInput"
                    class="d-none"
                    multiple
                    accept="*"
                    @change="handleFileChange"
                  />
                  <el-button
                    plain
                    size="small"
                    class="mb-1"
                    icon="el-icon-upload2"
                    style="height: 100%"
                    :disabled="saveLoading"
                    @click="handleSelectFile"
                  >
                    上传
                  </el-button>
                </div>
                <div class="flex-1 bg-light p-2 rounded">
                  <div v-for="(file, i) in areadyFiles" :key="file.url" class="file-item">
                    <attach-item :attach-data="file"></attach-item>
                    <el-button type="text" :disabled="saveLoading" @click="handleDeleteFile(1, i)">
                      删除
                    </el-button>
                  </div>
                  <div v-for="(file, index) in uploadFiles" :key="index" class="file-item">
                    <attach-item :attach-data="file"></attach-item>
                    <el-button
                      type="text"
                      :disabled="saveLoading"
                      @click="handleDeleteFile(2, index)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
            </template>
          </td>
        </tr>
      </tbody>
    </table>
    <div class="text-center my-3" v-if="!isView">
      <el-button class="btn-long" type="primary" :loading="saveLoading" @click="submit">
        {{ dataId ? '修改' : '保存' }}
      </el-button>

      <el-button class="btn-long" @click="beforClose">取消</el-button>
    </div>
  </div>
</template>

<script>
import { fileAdapter, attachAdapter } from '@/bank/components/attach/index'
import { revokeObjectURL } from '@/common/plugins/tools/file'
import { uploadOss, deleteOss } from '@/common/api/oss'
import AttachItem from '@/bank/components/attach/Item'
import { arrayFromString, arrayToString, add } from '@vimi/utils-tool'

import { updateFlow, addFlow } from '@/credit/views/county/settle/bond/component/refund/index'
import { mapGetters } from 'vuex'
export default {
  components: {
    AttachItem,
  },
  props: {
    registerId: String,
    unData: {
      type: Object,
      default: () => ({}),
    },
    viewMode: Boolean,
    otherEdit: Boolean,
  },
  data() {
    return {
      loading: false,
      saveLoading: false,
      registerData: {},
      formData: {},
      uploadFiles: [],
      areadyFiles: [],
      deleteFiles: [],
    }
  },
  computed: {
    ...mapGetters(['user']),
    totalFunds() {
      return add(
        this.formData.reach_principal,
        this.formData.reach_interest,
        this.formData.other_fee
      )
    },

    guaType() {
      return +this.related.gua_type
    },

    isView() {
      return this.viewMode || this.otherEdit
    },
    tdClass() {
      return this.isView ? '' : 'report-input-td'
    },
    dataId() {
      return this.unData.id || ''
    },
  },
  watch: {
    registerId: {
      handler: function () {
        this.getData()
      },
      immediate: true,
    },
    unData: {
      handler: function (val) {
        this.formData = { ...val }

        this.areadyFiles = arrayFromString(val.attachment).reduce((prev, curr) => {
          prev.push(
            attachAdapter({
              attachment: curr,
            })
          )
          return prev
        }, [])
      },
      immediate: true,
      deep: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    getData() {
      this.registerData = {}
      if (!this.registerId) {
        return
      }
      this.$api
        .getDataFromId(this.$serviceName, 'capital_pool_register', this.registerId)
        .then(res => {
          this.registerData = res?.data || {}
        })
        .finally(() => {
          this.loading = false
        })
    },
    submit() {
      if (!this.validate()) {
        return false
      }

      const promises = this.uploadFiles.map(it =>
        uploadOss({
          file: it.file,
          dir: `credit/unload/${this.queryId}`,
          type: 0,
          progress: ({ percent }) => {
            it.percent = percent
            it.loading = percent < 100
          },
        })
      )
      this.saveLoading = true
      return Promise.all(promises)
        .then(list => {
          const attachment = arrayToString([...this.areadyFiles.map(it => it.url), ...list])

          const data = {
            bus_type: 3,
            customer_name: this.registerData.agency_name,
            // customer_related_id: this.registerData.agency_id,
            related_id: this.registerId,
            attachment: attachment || '',
            receive_bank_name: this.formData.receive_bank_name,
            receive_account_name: this.formData.receive_account_name,
            receive_account: this.formData.receive_account,
            pay_fee_type: 2,
            pay_time: this.formData.pay_time,
            pay_funds: this.formData.pay_funds,
            remark: this.formData.remark,
          }
          return this.dataId
            ? updateFlow(this.dataId, data)
            : addFlow({
                ...data,
                approval_status: 1,
                submit_person_name: this.user.realName,
              })
        })
        .then(() => {
          if (!this.otherEdit) {
            this.$emit('success')
            this.$message.success('保存成功')
          }
        })
        .finally(() => {
          this.deleteOssFiles()
          this.saveLoading = false
        })
    },
    validate() {
      const enumValidator = {
        pay_time: '请选择退费时间',
        pay_funds: '请输入退费金额',
      }
      for (const key of Object.keys(enumValidator)) {
        if (!this.formData[key]) {
          this.$message.error(enumValidator[key])
          return false
        }
      }

      return true
    },
    beforClose() {
      this.$emit('dismiss')
    },
    deleteOssFiles() {
      if (!this.deleteFiles.length) return
      deleteOss(this.deleteFiles.map(it => it.url))
    },
    handleDeleteFile(type, index) {
      if (type === 2) {
        const file = this.uploadFiles[index]
        revokeObjectURL(file.url)
        this.uploadFiles.splice(index, 1)
      } else {
        this.deleteFiles.push(...this.areadyFiles.splice(index, 1))
      }
    },
    handleSelectFile() {
      const { uploadInput } = this.$refs
      uploadInput.click()
    },
    handleFileChange(e) {
      const { files = [] } = e.target

      for (let i = 0; i < files.length; i++) {
        this.uploadFiles.push(fileAdapter(files[i]))
      }

      this.resetInput()
    },
    resetInput() {
      const { uploadInput } = this.$refs
      if (uploadInput) {
        uploadInput.value = ''
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.file-item {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px dotted #eee;

  &:last-child {
    border-bottom: none;
  }
}
.approve-table {
  text-align: center;
  margin-bottom: 0;
  margin-top: -1px;
  td {
    vertical-align: middle;
  }
}
</style>
